package com.syqc.comlib.custom

import android.content.Context
import android.view.Gravity
import android.widget.Toast
import java.lang.ref.WeakReference

object MToast {
    //    https://www.jianshu.com/p/6fd3dc007850
//    https://github.com/getActivity/XToast
    private var mToast: Toast? = null
    private var weakReference: WeakReference<Context>? = null

    fun cancel() {
        if (mToast != null) {
            mToast!!.cancel()
            mToast = null
        }
    }

    fun showShortToast(context: Context, message: String) {
        show(context, message)
    }

    fun showLongToast(context: Context, message: String) {
        show(context, message, Toast.LENGTH_LONG)
    }

    /**
     * 展示提示
     */
    private fun show(
        context: Context,
        message: String,
        duration: Int = Toast.LENGTH_SHORT
    ) {
        if (mToast == null || weakReference == null || weakReference!!.get() == null) {
            weakReference = WeakReference(context)
            mToast = Toast.makeText(context, message, duration)?.apply {
                setGravity(Gravity.CENTER, 0, 0)
                show()
            }
        } else {
            mToast!!.setText(message)
            mToast!!.show()
        }
    }
}